<template>
  <li class="todo-item">
    <input type="checkbox" :checked="done" @click="handleChange" />
    <span v-if="!isEditing" @click="isEditing = true" :class="{ delete: done === true }">{{ content }}</span>
    <input
      v-else
      type="text"
      :value="content"
      @blur="handleEdit"
      @keyup.enter="handleEdit"
      v-focus
    />
    <button @click="handleDelete">删除</button>
  </li>
</template>

<script setup>
import { ref } from 'vue'
const props = defineProps({
  id: {
    type: Number,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
  // 表示待办事项的完成状态
  done: {
    type: Boolean,
    required: true,
  },
})
const emit = defineEmits(['update', 'toggle','delete'])
const isEditing = ref(false)
const handleEdit = (event) => {
  // 更新content值,不能直接在此更新（因为它只读），需要把数据传回父组件后更改
  emit('update', props.id, event.target.value)
  // 更新isEditing值
  isEditing.value = false
}

// 自定义指令使用v开头，vFoucus
const vFocus = {
  //指令的生命周期函数: 当指令绑定的元素在挂载到dom完成时调用
  mounted(el) {
    // el是当前指令作用的元素,调用input的focus方法，获得焦点
    el.focus()
  },
}
// 选择框状态改变
const handleChange = (event) => {
  emit('toggle', props.id, 
  event.target.checked) //复选框的当前选中状态（布尔值）
}

const handleDelete=()=>{
 emit('delete',props.id)
}
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 40px;
  list-style: none;
  border-bottom: 1px solid #eee;
}
.todo-item span,
.todo-item input[type='text'] {
  flex: 1;
  margin: 0 20px;
}
.todo-item button {
  padding: 0 10px;
}
.todo-item:hover {
  background-color: rgb(221, 221, 221);
  color: rgb(169, 39, 255);
}
.delete {
  text-decoration: line-through;
  color: crimson;
}
</style>
